package com.example.springboot.service;

/**
 * 功能:
 * 作者：jian
 * 日期：2024/3/14 15:28
 */
/**
@Service
public class UserService1 {

    @Autowired
    UserMapper userMapper;

    public void insertUser(User user){
        userMapper.insert(user);
    }

    public void updateUser(User user){
        userMapper.updateUser(user);
    }

    public List<User> findUser() {
        return userMapper.findAll();
    }

    public User findUser(Integer id) {
        return userMapper.findUserById(id);
    }

    public void deleteUser(Integer id) {
         userMapper.deleteById(id);
    }

    public void batchDeleteUser(List<Integer> ids) {
        for (Integer id : ids) {
            userMapper.batchDeleteUser(id);
        }

    }

    public List<User> findUserByMore(String username,String name) {
       return userMapper.findUserByMo(username,name);

    }

    public List<User> selectMo(String username, String name) {
        return userMapper.selectByMo(username,name);
    }


//    MySQL处理分页的时候，一般的逻辑是：
//    limit 10,10 - 查询出 10 + 10 条数据，然后丢弃掉前 10 条。
//    limit 20,10 - 查询出 20 + 10 条数据，然后丢弃掉前 20 条。
    public Page getPage(Integer pageNum,Integer pageSize,String username, String name) {
        Integer skpNum = (pageNum-1)*pageSize;//计算出来
        Page<User> page = new Page<>();

        List<User> userList = userMapper.getPage(skpNum, pageSize, username, name);
        Integer total = userMapper.getCountPage(username, name);

        page.setTotal(total);
        page.setList(userList);
        return page;
    }

//验证用户账户是否合法
    public User login(User user) {
       User dbUser=  userMapper.selectByUsername(user.getUsername());
       if (dbUser==null){
           //抛出一个自定义异常
           throw new ServiceException("账号不存在");
       }
       if (!user.getPassword().equals(dbUser.getPassword())){
           throw new ServiceException("用户名或密码错误");
       }
       //生成token
        String token = TokenUtils.createToken(dbUser.getId().toString(),dbUser.getPassword());
       dbUser.setToken(token);
        return  dbUser;
    }

    public User register(User user) {
        User dbUser=  userMapper.selectByUsername(user.getUsername());
        if (dbUser!=null){
            //抛出一个自定义异常
            throw new ServiceException("用户名已存在");
        }
        user.setName("honey-"+ RandomUtil.randomNumbers(4));
        userMapper.insert(user);
        return user;
    }

    public void resetPassword(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (dbUser==null){
            //抛出一个自定义异常
            throw new ServiceException("用户名不存在");
        }
        if(!user.getPhone().equals(dbUser.getPhone())){
            throw new ServiceException("验证错误");
        }
        dbUser.setPassword("123"); //重置密码
        userMapper.updateUser(dbUser);


    }
}
 */